package com.ply.flashsalessystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ply.flashsalessystem.annotation.AuthorityName;
import com.ply.flashsalessystem.annotation.UserAuthority;
import com.ply.flashsalessystem.entity.dto.AddGoods;
import com.ply.flashsalessystem.entity.pojo.Goods;
import com.ply.flashsalessystem.entity.pojo.Tag;
import com.ply.flashsalessystem.entity.result.Result;
import com.ply.flashsalessystem.entity.status.GoodsPutAwayStatus;
import com.ply.flashsalessystem.entity.vo.manage.GoodsVO;
import com.ply.flashsalessystem.entity.wrapper.GoodsWrapper;
import com.ply.flashsalessystem.exception.GoodsException;
import com.ply.flashsalessystem.service.GoodsService;
import com.ply.flashsalessystem.service.TagService;
import com.ply.flashsalessystem.service.ossService.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author XiaoPan
 * @since 2022-03-23
 */
@RestController
@RequestMapping("/goods")
@CrossOrigin
@Api("商品接口")
public class GoodsController {
    @Autowired
    GoodsService goodsService;

    @Autowired
    FileService fileService;

    @Autowired
    TagService tagService;

    /**
     * 对商品的管理 增删改查
     */
    @AuthorityName(authorityId = 1,authorityName = "增加商品")
    @PostMapping("addGoods")
    @ApiOperation("增加商品 admin")
    public Result addGoods(AddGoods goods1,
                           MultipartFile file) {
        Goods goods = Goods.addGoodToGoods(goods1, null);
        if (file != null){
            String img = fileService.upload(file);
            goods.setImage(img);
        }
        //增加的时候 不需要商品id
        return goodsService.addGoods(goods)
                ? Result.ok().message("商品添加成功")
                : Result.error().message("商品添加失败");
    }

    //逻辑删除
    @AuthorityName(authorityId = 2,authorityName = "逻辑删除商品")
    @ApiOperation("逻辑删除商品")
    @DeleteMapping("deleteGoods/{goodId}")
    public Result deleteForShopCar(@PathVariable("goodId") Integer goodId) {
        return goodsService.removeById(goodId)
                ? Result.ok().message("删除购物车成功")
                : Result.error().message("删除购物车失败");
    }

    //下架商品
    @AuthorityName(authorityId = 3,authorityName = "下架商品")
    @PostMapping("outAwayGoods/{goodId}")
    @ApiOperation("下架 商品 admin")
    public Result outAwayGoods(@PathVariable("goodId") Integer goodId) {
        return goodsService.outAwayGoods(goodId)
                ? Result.ok().message("商品下架成功")
                : Result.error().message("商品下架失败");
    }

    //上架商品
    @AuthorityName(authorityId = 4,authorityName = "上架商品")
    @PostMapping("putAwayGoods/{goodId}")
    @ApiOperation("上架商品 商品 admin")
    public Result putAwayGoods(@PathVariable("goodId") Integer goodId) {
        return goodsService.putAwayGoods(goodId)
                ? Result.ok().message("上架商品成功")
                : Result.error().message("上架商品成功");
    }


    // 不允许这样做 需要详细修改 那一个 商品的 哪一个数据
    // 上架后的商品 可不可以 修改呢 可以修改的
    @AuthorityName(authorityId = 5,authorityName = "修改商品")
    @ApiOperation("修改商品")
    @PutMapping("updateGoods/{goodId}")
    public Result updateGoods(@PathVariable("goodId") Integer goodId,
                              @RequestBody Goods goods,
                              MultipartFile file) {
        // 查看有没有 商品 查询 id
        Goods byId = goodsService.getById(goodId);
        if (byId == null) {
            return Result.error().message("商品id 不存在 或者 商品被删除");
        }
        // 余额
        if (goods.getRemainNums() != null){
            if (goods.getRemainNums() <= 0){
                return Result.error().message("库存量 不可以为负数");
            }
            byId.setRemainNums(goods.getRemainNums());
        }
        // 价格 : price
        if (goods.getPrice() != null){
            if (goods.getPrice() <= 0){
                return Result.error().message("价格 不可以为负数");
            }
            byId.setPrice(goods.getPrice());
        }
        // minSales
        if (goods.getMinSales() != null){
            if (goods.getMinSales() <= 0){
                return Result.error().message("最少 售卖 不可以为负数");
            }
            byId.setMinSales(goods.getMinSales());
        }

        // defaultRemain
        if (goods.getDefaultRemain() != null){
            if (goods.getDefaultRemain() <= 0){
                return Result.error().message("默认余量 不可以为负数");
            }
            byId.setDefaultRemain(goods.getDefaultRemain());
        }

        // 判断 name 是否 相同
        String name = byId.getName();
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Goods one = goodsService.getOne(queryWrapper);
        if (one != null){
            if (!Objects.equals(one.getGoodsId(), byId.getGoodsId())) {
                throw new GoodsException("商品修改失败,已有商品name");
            }
        }

        byId.setName(goods.getName());
        //分类
        Integer tagId = goods.getTagId();
        Tag byId1 = tagService.getById(tagId);
        if (byId1 != null){
            byId.setTagId(tagId);
        }

        // 更新 img
        if (file != null){
            String img = fileService.upload(file);
            byId.setImage(img);
        }
        byId.setDetails(goods.getDetails());

        return goodsService.updateGoods(byId)
                ? Result.ok().message("商品修改成功")
                : Result.error().message("商品修改失败");
    }


    // 分 管理员 还是 普通用户 普通用户 不需要 所有数据 有些数据 普通用户 不需要看 重新建vo类 给普通用户   管理员
    @AuthorityName(authorityId = 7,authorityName = "管理员 条件分页所有商品列表")
    @ApiOperation("条件分页所有商品列表, 没有分页条件 就默认 0页 10个")
    @PostMapping(value = {"queryGoodsAllPageByOdds/{current}/{limit}", "/queryGoodsAllPageByOdds"})
    public Result queryGoodsAllPageByOdds(@PathVariable(value = "current", required = false) Integer current,
                                          @PathVariable(value = "limit", required = false) Integer limit,
                                          @RequestBody(required = false) GoodsWrapper goodsWrapper) {
        if (goodsWrapper == null) {
            goodsWrapper = new GoodsWrapper();
        }
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        Page<GoodsVO> page = goodsService.queryGoodsAll(current, limit, goodsWrapper);
        List<GoodsVO> goodsVOS = GoodsVO.addPutAwayString(page.getRecords());

        return Result.ok().message("查询成功")
                .data("total", page.getTotal())
                .data("rows", goodsVOS);
    }


//    @AuthorityName(authorityId = 6,authorityName = "条件分页所有商品列表 用户")
    @UserAuthority
    @ApiOperation("用户 条件分页所有商品列表, 没有分页条件 就默认 0页 10个")
    @PostMapping(value = {"user/queryGoodsAllPageByOdds/{current}/{limit}", "user/queryGoodsAllPageByOdds"})
    public Result queryGoodsAllPageByOddsUser(@PathVariable(value = "current", required = false) Integer current,
                                              @PathVariable(value = "limit", required = false) Integer limit,
                                              @RequestBody(required = false) GoodsWrapper goodsWrapper) {
        if (goodsWrapper == null) {
            goodsWrapper = new GoodsWrapper();
        }
        if (current == null || limit == null) {
            current = 0;
            limit = 10;
        }
        goodsWrapper.setPutAway(GoodsPutAwayStatus.DO_AWAY);
        Page<GoodsVO> page = goodsService.queryGoodsAll(current, limit, goodsWrapper);
        List<GoodsVO> goodsVOS = GoodsVO.addPutAwayString(page.getRecords());

        return Result.ok().message("查询成功")
                .data("total", page.getTotal())
                .data("rows", goodsVOS);
    }



}

